<template>
	<view :style="objColor">
		<!-- components/payment/payment.wxml -->
		<view class="setting1">
			<view class="setting_title">
				<view>充值</view>
				<view class="sub-tips">充值金额可能出现延迟到账情况，请稍作等待</view>
			</view>
			
			<!-- 营销获客 活动 -->
			<view class="message" style="margin-top: 10rpx;" v-if="czjlDetail.lowAmount">
				<view class="btn">限时优惠</view>
				<view class="title">
					充值满
						<text class="num_text">{{ czjlDetail.lowAmount }}元</text>
						，
			
						<!-- 奖励方式 -->
						<text v-if="czjlDetail.bonus">
							送奖励金
							<text class="num_text">{{ czjlDetail.bonus }}元</text>
							，
						</text>
						<text v-if="czjlDetail.couponCount">
							送优惠券
							<text class="num_text">{{ czjlDetail.couponCount }}张</text>
							，
						</text>
						<text v-if="czjlDetail.integral">
							送积分
							<text class="num_text">{{ czjlDetail.integral }}分</text>
							，
						</text>
						<text v-if="czjlDetail.serviceFeeCount">
							送免服务费
							<text class="num_text">{{ czjlDetail.serviceFeeCount }}次</text>
							，
						</text>
			
						<!-- 奖励方式最高 -->
						<text v-if="czjlDetail.highestStatus == 1">
							<text v-if="czjlDetail.highestBonus">
								最高送奖励金
								<text class="num_text">{{ czjlDetail.highestBonus }}元</text>
								，
							</text>
							<text v-if="czjlDetail.highestCouponCount">
								最高送优惠券
								<text class="num_text">{{ czjlDetail.highestCouponCount }}张</text>
								，
							</text>
							<text v-if="czjlDetail.highestIntegral">
								最高送积分
								<text class="num_text">{{ czjlDetail.highestIntegral }}分</text>
								，
							</text>
							<text v-if="czjlDetail.highestServiceFeeCount">
								最高送免服务费
								<text class="num_text">{{ czjlDetail.highestServiceFeeCount }}次</text>
								，
							</text>
						</text>
				</view>
				<view class="info" @tap="toPayAward" :data-hdid="czjlDetail.activityId">详情 ></view>
			</view>
			
			<view class="priceType">
				<view :class="'type ' + (priceType == index ? 'type_action' : '')" :data-index="index"
					@tap="checkPriceType" v-for="(item, index) in priceTypeList" :key="item.payment">
					{{ item }}元
				</view>
				<view class="custom">
					<image class="custom_img" src="https://oos-cn.ctyunapi.cn/front-end/static/static/Editor.png"></image>
					<input class="custom_input" type="digit" :value="customPrice" @input="getCustomPrice"
						placeholder="自定义" />
					元
				</view>
			</view>
			<view class="setting_btn" @tap="parseEventDynamicCode($event, submitStatus ? 'toCharge' : '')">立即充值</view>
		</view>

		<!-- 充值中 -->
		<view class="recharge-loading" v-if="rechargeLoading">
			<view class="body">
				<image class="icon" src="https://oos-cn.ctyunapi.cn/front-end/static/static/recharge.png" mode="widthFix"></image>
				<view class="title">正在充值</view>
				<view class="desc">请勿关闭程序或窗口</view>
			</view>
		</view>
		<!-- 充值异常 -->
		<view class="recharge-error" v-if="rechargeError">
			<view class="body">
				<view class="title">
					<text>充值异常</text>
					<image class="close" src="https://oos-cn.ctyunapi.cn/front-end/static/static/close.png" mode="widthFix"
						@tap.stop.prevent="closeRechargeError"></image>
				</view>
				<view class="content">
					<view class="msg">{{ remark }}</view>
					<view class="phone">
						<text v-if="showStatus && phoneNumber">客服电话：{{ phoneNumber }}</text>
					</view>
				</view>
				<button class="btn" style="margin:0"
					@tap.stop.prevent="calltel">{{ showStatus && phoneNumber ? '呼叫客服' : '我知道了' }}</button>
			</view>
		</view>
	</view>
</template>

<script>
	'use strict';

	// exports.__esModule = true; // components/payment/payment.ts
	var https_1 = require('./../../api/https.js');
	var Interval = null;
	import { getRechargeRewardMemo } from '@/api/marketing/rechargeApi';
	import { recharge, rechargeBefore } from '@/api/marketing/marketing';
	const dayjs = require('@/utils/dayjs.min.js'); 
	const app = getApp()
	export default {
		data() {
			return {
				priceType: 0,
				customRechargePrice: 30,
				priceTypeList: [30, 50, 100, 150],
				customPrice: '',
				orderNo: '',
				getRechargeResultNum: 1,
				rechargeLoading: false,
				rechargeError: false,
				remark: '',
				phoneNumber: '',
				showStatus: false,
				submitStatus: true,
				czjlDetail:null,
				// 充值统计参数
				rechargeQuery: {
				    joinChannel: 3,
				    //:0:iosapp;1:安卓app;2:微信公众号;3:小程序;
				    rechargeAmount: 0,
				    //	充值金额
				    rechargeTime: '',
				    //充值时间 yyyy-MM-dd HH:mm:ss,
				    sellerId: app.globalData.sellerId //商家ID
				},
			};
		},
		
		/**
		 * 组件的属性列表
		 */
		props: {},
		// 生命周期函数，可以为函数，或一个在 methods 段中定义的方法名
		beforeMount: function() {
			// var that = this;
			// https_1.selectAbnormalConfig().then(function(res) {
			// 	if (res.code == 0 && res.data) {
			// 		that.remark = res.data.remark,
			// 			that.phoneNumber = res.data.telephone,
			// 			that.showStatus = res.data.showStatus === 1 ? true : false
			// 	}
			// });
				
			if (uni.getStorageSync('token')) {
				var that = this;
				https_1.selectAbnormalConfig().then(function(res) {
					if (res.code == 0 && res.data) {
						that.remark = res.data.remark,
							that.phoneNumber = res.data.telephone,
							that.showStatus = res.data.showStatus === 1 ? true : false
					}
				});
				this.getPayAwardMsg()
			}

		},
		/**
		 * 组件的方法列表
		 */
		methods: {
			//获取充值活动
			getPayAwardMsg() {
				let userInfo = uni.getStorageSync('userInfo');
				console.log(userInfo);
				if (userInfo.memberType == 0) {
					this.userTypes = '1';
				} else {
					this.userTypes = '2';
				}
				getRechargeRewardMemo({
					plUserId: uni.getStorageSync('memberId'),
					userType: this.userTypes,
					cityId:uni.getStorageSync('cityId1')
				})
					.then((res) => {
						if (res.code == 200) {
							console.log(res.data, '获取充值活动........11');
							this.setData({
								czjlDetail: res.data
							});
						}
					})
					.catch((err) => {
						console.log(err);
					});
			},
			
			toPayAward(e) {
				console.log(e.currentTarget.dataset, 'cccccc');
				uni.navigateTo({
					url: '/marketing_page/pages/pay/payAward/payAward?HD=' + `${e.currentTarget.dataset.hdid}`
				});
			},
			//选择充值类型
			checkPriceType: function(e) {
				var index = e.currentTarget.dataset.index;
				this.priceType = index,
					this.customRechargePrice = this.priceTypeList[index],
					this.customPrice = ''
			},
			//输入时触发（自定义充值金额）
			getCustomPrice: function(e) {
				var num = e.detail.value;
				var x = String(num).indexOf('.') + 1; //得到小数点的位置
				if (x) {
					var y = String(num).length - x; //小数点的位数
					if (y > 2) {
						var that_1 = this;
						uni.showModal({
							title: '消息提示',
							content: '自定义金额小数位不能大于2位',
							showCancel: false,
							success: function(res) {
								if (res.confirm) {
									that_1.customPrice = '',
										that_1.customRechargePrice = 30,
										that_1.priceType = 0
								}
							}
						});
					}
				}
				this.priceType = -1,
					this.customPrice = e.detail.value,
					this.customRechargePrice = e.detail.value
			},
			// APP唤起微信授权
			wxGetUserInfo() {
				let that = this
				return new Promise((resolve, reject) => {
					uni.getProvider({
						service: 'oauth',
						success: function(res) {
							if (~res.provider.indexOf('weixin')) {
								uni.login({
									provider: 'weixin',
									success: function(loginRes) {
										uni.getUserInfo({
											provider: 'weixin',
											success: function(infoRes) {
												let userInfo = {
													...infoRes.userInfo,
													...loginRes.authResult
												}
												resolve(userInfo)
												uni.setStorageSync('openId', userInfo.openId)
												uni.setStorageSync('unionId', userInfo.unionId)
												that.toCharge()
												console.log(userInfo, '用户信息');
											},
											fail(err) {
												reject(err)
												console.log(err,
													'getUserInfoError')
											}
										})
									},
									fail(err) {
										reject(err)
										console.log(err, 'loginError')
									}
								})
							}
						},
						fail(err) {
							reject(err)
							console.log(err, 'getProviderError')
						}
					})
				})
			},
			//立即充值
			toCharge: function() {
				// return wx.removeStorageSync('openId')
				this.submitStatus = false
				var that = this;
				var chargePrice = 0;

				if (that.customRechargePrice !== '' && that.customRechargePrice > 0) {
					chargePrice = that.customRechargePrice * 100;
				} else {
					uni.showToast({
						title: '请选择充值金额',
						icon: 'none'
					});
					that.submitStatus = true
					return false;
				}

				// let openId = uni.getStorageSync("openId")
				// if (!openId) { //获取不到openid就轮询
				// uni.showLoading({
				// 	title: '加载中...'
				// });
				//  setTimeout(()=>{
				// 		this.wxGetUserInfo()
				// 		 },500)
				// 		console.log("进入openid")
				// 		that.submitStatus = true
				// 	return false;
				// }
				// wx.hideLoading()
				//#ifdef MP-WEIXIN
				let type = 'JSAPI'
				let openId = uni.getStorageSync("openId")
				if (!openId) { //获取不到openid就轮询
					uni.showLoading({
						title: '加载中...'
					});
					that.submitStatus = true
					 getApp().uniLogin().then(res=>{
					 	setTimeout(that.toCharge,500)
					 }).catch(err=>{
						setTimeout(that.toCharge,500)
					 })
					console.log("进入openid")
					
					return false;
				}
				uni.hideLoading();
				//#endif
				
				//#ifdef APP-PLUS
				let type = 'APP'
				//#endif
				console.log(type)
				https_1
					.unifiedOrders({
						openId: uni.getStorageSync("openId"), // oGIXrv6BHN7TW8s_5G_u7zwlgl_4
						totalFee: chargePrice,
						tradeType: type ,// 交易类型：JSAPI -JSAPI支付 NATIVE -Native支付 APP -APP支付
					})
					.then((res)=> {
						console.log(res)
						console.log("进入app充值1", res.code,uni.getStorageSync('openId'))
						if (res.code == 0) {
							uni.showModal({
								title: res.msg,
								content: res.data,
								showCancel: false,
								success(res1) {
									if (res1.confirm) {
										that.submitStatus = true
									}
								}
							});
							//微信
							//#ifdef MP-WEIXIN
							var getpar = {
								timeStamp: res.data.timeStamp,
								nonceStr: res.data.nonceStr,
								package: res.data.package,
								paySign: res.data.sign,
								orderNo: res.data.orderNo
							};
							//#endif
							//APP
							//#ifdef APP-PLUS
							console.log("进入app充值", res.data)
							var getpar = {
								"appid": res.data.appid, // 微信开放平台 - 应用 - AppId，注意和微信小程序、公众号 AppId 可能不一致
								"noncestr": res.data.noncestr, // 随机字符串
								"package": res.data.package, // 固定值
								"partnerid": res.data.partnerid, // 微信支付商户号
								"prepayid": res.data.prepayid, // 统一下单订单号
								"timestamp": res.data.timestamp, // 时间戳（单位：秒）
								"sign": res.data.sign // 签名，这里用的 MD5/RSA 签名
							};                                                                                             
							//#endif
							that.orderNo = res.data.orderNo,
							that.submitStatus = true
							
							if(that.marketingSwitch) {
								
								//   营销获客处理
								setTimeout(()=>{
									that.rechargeQuery.rechargeAmount = chargePrice;
									that.rechargeQuery.sellerId = app.globalData.sellerId;
									that.rechargeQuery.rechargeTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
									that.rechargeQuery.orderNo = res.data.orderNo;
									that.rechargeBefore();
								})
							}
							that.gopay(getpar);
						} else {
							that.submitStatus = true
							uni.showModal({
								title: '消息提示',
								content: res.msg,
								showCancel: false,
								success(res1) {
									if (res1.confirm) {
										that.submitStatus = true
									}
								}
							});
						}
					});
			},
			//取消充值 -- 支付前
			cancelCharge: function() {
				let that = this
				https_1
					.unifiedOrders({
						// openId: uni.getStorageSync('openid'),
						totalFee: this.customRechargePrice * 100,
						tradeType: 'APP',
						orderNo: this.orderNo,
						cancelRecharge: 2
					})
					.then((res)=> {
						if (res.code == 0) {
							that.submitStatus = true
							that.rechargeLoading = false
							that.rechargeError = true
							// uni.showModal({
							// 	title: '消息提示',
							// 	content: '已取消充值',
							// 	showCancel: false
							// });
						}
					});
			},
			//取消充值 -- 支付后
			onCancelRecharge: function() {
				var that = this;
				https_1
					.cancelRecharge({
						orderNo: this.orderNo
					})
					.then(function() {
						that.submitStatus = true
						that.rechargeLoading = false
						that.rechargeError = true
						// uni.showToast({
						// 	title: '充值失败',
						// 	icon: 'none'
						// });
					});
			},
			//调起支付
			gopay: function(data) {
				var that = this;
				that.getRechargeResult()
				// console.log("222" + JSON.stringify(data))
				//#ifdef APP-PLUS
				//APP
				var _data = JSON.stringify(data)
				uni.requestPayment({
					provider: 'wxpay',
					orderInfo: _data, //微信、支付宝订单数据 【注意微信的订单信息，键值应该全部是小写，不能采用驼峰命名】
					success: function(res) {
						// that.getRechargeResult();
					},
					complete(){
						// that.getRechargeResult();
					},
					fail: function(err) {
						// 定义支付失败状态
						that.payErr = true
					}
				});
				//#endif

				//微信小程序
				//#ifdef MP-WEIXIN
				uni.requestPayment({
					timeStamp: data.timeStamp + '',
					nonceStr: data.nonceStr,
					package: data.package,
					signType: 'MD5',
					paySign: data.paySign,
					success: function () {
						// that.getRechargeResult();
					},
					complete(){
						// that.getRechargeResult();
					},
					fail: function () {
						// 定义支付失败状态
						that.payErr = true
					}
				});
				//#endif
			},
			//查询充值结果
			getRechargeResult: function() {
				var that = this;
				this.rechargeLoading = true
				// uni.showLoading({title:'充值中..',mask:true})
				this.getUserMoney();
			},
			// 轮询支付状态
			rollPolingPayStatus(){
				let that = this
				setTimeout(()=>{
					if(that.payErr){
						that.payErr = false
						that.cancelCharge();
						return
					}
					this.getUserMoney()
				},1500)
			},
			getUserMoney: function() {
				var that = this;
				https_1
					.orderResultQuery({
						orderNo: this.orderNo
					})
					.then(function(res) {
						if (res.code === 0) {
							uni.hideLoading()
							// clearInterval(that.Interval);
							if(that.marketingSwitch) {
								that.notificationRecharge();
							}
							that.submitStatus = true
							that.rechargeLoading = false,
							that.getRechargeResultNum = 1,
							that.customPrice = '',
							that.priceType = 0,
							that.customRechargePrice = 30
							uni.showModal({
								title: '消息提示',
								content: '充值成功',
								showCancel: false
							});
							that.$emit('getbalance');
						}else{
							that.rollPolingPayStatus()
						}
					}).catch(()=>{
						// 接口报错处理
						that.rollPolingPayStatus()
					});
			},
			// 关闭充值异常
			closeRechargeError: function() {
				this.rechargeError = false
			},
			
			// 充值之前通知营销获客充值成功
			rechargeBefore() {
			    console.log('充值之前通知营销获客充值成功');
			    rechargeBefore(this.rechargeQuery).then((res) => {
			        console.log(res, '充值之前通知营销获客充值成功啦啦啦');
			    });
			},
			
			// 支付成功后通知营销获客充值成功
			notificationRecharge() {
			    console.log('支付成功后通知营销获客充值成功');
			    recharge(this.rechargeQuery).then((res) => {
			        console.log(res, '支付成功后通知营销获客充值成功啦啦啦');
			    });
			},
			// 客服
			calltel: async function() {
				if (this.phoneNumber) {
					//#ifdef APP-PLUS
						let result = await this.$store.dispatch("requestPermissions",'CALL_PHONE')
						if (result !== 1){
							return
						}else{
							uni.makePhoneCall({
								phoneNumber: this.phoneNumber
							});
						}    
					//#endif
					//#ifdef MP-WEIXIN
						uni.makePhoneCall({
							phoneNumber: this.phoneNumber
						});
					//#endif
					
				} else {
					this.closeRechargeError();
				}
			}
		}
	};
</script>
<style lang="less" scoped>
	/* components/payment/payment.wxss */
	/*颜色*/
	/*数字*/
	/*文字溢出隐藏*/
	/*固定布局*/
	/* grid是（布局 */
	/*宽高*/
	/* 字体大小*/
	/* 行高 */
	/* 圆角 */
	/* 外边距 */
	/* 内边距 */
	/* 实边框 */
	/* 虚边框 */
	/* 定位  */
	/* 数组  */
	.record-in .aaa1 {
		color: #909399;
	}

	.record-in .aaa2 {
		color: var(--textColor);
	}

	.record-in .aaa3 {
		color: #f7a14a;
	}

	.record-in .aaa4 {
		color: #72c23d;
	}

	.record-in .aaa5 {
		color: #606266;
	}

	.setting1 .setting_title {
		display: flex;
		font-size: 34rpx;
		font-family: PingFang SC;
		font-weight: bold;
		color: #1a1a1a;
	}

	.setting1 .setting_title .sub-tips {
		font-size: 24rpx;
		color: #909399;
		margin-left: 20rpx;
	}

	.setting1 .priceType {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		padding: 20rpx;
	}

	.setting1 .priceType .type {
		width: 168rpx;
		height: 64rpx;
		line-height: 64rpx;
		background: #f5f7fa;
		border-radius: 32rpx 32rpx 32rpx 32rpx;
		text-align: center;
		font-size: 30rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #606266;
		margin: 36rpx 0 0 0;
	}

	.setting1 .priceType .type_action {
		background: rgba(20, 135, 250, 0.06);
		border: 1rpx solid var(--textColor);
		border-radius: 32rpx 32rpx 32rpx 32rpx;
		font-size: 30rpx;
		font-family: PingFang SC;
		font-weight: bold;
		color: var(--textColor);
	}

	.setting1 .priceType .custom {
		display: flex;
		align-items: center;
		margin-top: 36rpx;
		margin-right: 160rpx;
		font-size: 30rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #606266;
	}

	.setting1 .priceType .custom .custom_img {
		margin-left: 23rpx;
		width: 26rpx;
		height: 27rpx;
	}

	.setting1 .priceType .custom .custom_input {
		width: 150rpx;
		text-align: center;
		font-size: 28rpx;
		color: #606266;
		border-bottom: 1rpx solid #606266;
	}

	.setting1 .setting_btn {
		font-size: 30rpx;
		font-family: PingFang SC;
		font-weight: bold;
		color: #fff;
		margin: 40rpx auto 0;
		width: 340rpx;
		height: 88rpx;
		line-height: 88rpx;
		text-align: center;
		background: var(--btnColor);
		/* background: linear-gradient(105deg, #2b99ff, #1b8cf5); */
		box-shadow: 0rpx 3rpx 6rpx 0rpx rgba(0, 110, 212, 0.3);
		border-radius: 44rpx;
	}

	.recharge-loading {
		position: fixed;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
		z-index: 999;
		background: rgba(0, 0, 0, 0.6);
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.recharge-loading .body {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		width: 630rpx;
		height: 522rpx;
		background: #ffffff;
		border-radius: 20rpx;
	}

	.recharge-loading .body .icon {
		width: 230rpx;
		height: 222rpx;
	}

	.recharge-loading .body .title {
		font-size: 32rpx;
		font-weight: bold;
		color: #18181a;
		margin-top: 24rpx;
	}

	.recharge-loading .body .desc {
		font-size: 26rpx;
		font-weight: 500;
		color: #fc724c;
		margin-top: 32rpx;
	}

	.recharge-error {
		position: fixed;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
		z-index: 999;
		background: rgba(0, 0, 0, 0.6);
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.recharge-error .body {
		width: 630rpx;
		background: #ffffff;
		border-radius: 20rpx;
		overflow: hidden;
	}

	.recharge-error .body .title {
		font-size: 34rpx;
		font-weight: bold;
		color: #fc724c;
		text-align: center;
		margin-top: 42rpx;
		margin-bottom: 16rpx;
		position: relative;
	}

	.recharge-error .body .title .close {
		position: absolute;
		top: -12px;
		right: 20rpx;
		width: 28rpx;
		height: 28rpx;
		padding: 14rpx;
	}

	.recharge-error .body .content {
		padding: 34rpx;
	}

	.recharge-error .body .content .msg {
		font-size: 30rpx;
		font-weight: 500;
		color: #303133;
		line-height: 44rpx;
	}

	.recharge-error .body .content .phone {
		font-size: 30rpx;
		font-weight: 500;
		color: #303133;
		line-height: 48rpx;
		margin: 50rpx 0 40rpx;
	}

	.recharge-error .body .btn {
		height: 110rpx;
		line-height: 110rpx;
		background: #ffffff;
		font-size: 30rpx;
		font-weight: bold;
		color: var(--textColor);
		border-top: 1px solid #dcdfe6;
		border-radius: 0;
	}

	.recharge-error .body .btn::after {
		border: 0;
	}
	
	.message{
		width: 100%;
		box-sizing: border-box;
		height: 64rpx;
		display: flex;
		align-items: center;
		background: rgba(252,114,76,0.08);
		padding: 0 24rpx;
		justify-content: space-between;
		.btn{
			width: 118rpx;
			height: 44rpx;
			background: #F7A14A;
			border-radius: 22rpx;
			font-size: 22rpx;
			color: #fff;
			text-align: center;
			line-height: 44rpx;
		}
		.title{
			width: 60%;
			text-overflow: ellipsis;
			white-space: nowrap;
			overflow: hidden;
			font-size: 22rpx;
			font-weight: bold;
			color: #FC724C;
		}
		.info{
			font-size: 22rpx;
			font-weight: 500;
			color: #F7A14A;
		}
	}
</style>
